package com.zzty.train.pjm.controller;


import com.zzty.train.pjm.entity.Clazz;
import com.zzty.train.pjm.entity.User;
import com.zzty.train.pjm.service.ClazzService;
import com.zzty.train.pjm.service.UserService;
import com.zzty.train.pjm.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.util.List;

@RestController
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    ClazzService clazzService;
    @Autowired
    UserService userService;
    //页面加载时获取所有班级
    @RequestMapping(value = "getClazz")
    public List<Clazz>getClazz(){
    List<Clazz>clazzes = clazzService.getClazz();
        System.out.println(clazzes);
    return clazzes;
    }
    //检测用户名是否重复
    @RequestMapping(value = "checkUserName")
    public String checkUserName(User user){
        System.out.println("user"+user.toString());
        User user1=userService.getUser(user);
        String name;
        if(user1==null){
            name="";
        }else{
            name=user1.getName();
        }
        return name;
    }
    //验证用户邮箱
    @RequestMapping(value = "checkEmail")
    public String checkEmail(User user){
        int a=(int)(Math.random()*10);
        int b=(int)(Math.random()*10);
        int c=(int)(Math.random()*10);
        int d=(int)(Math.random()*10);
        int e=(int)(Math.random()*10);
        int f=(int)(Math.random()*10);
        String a1=String.valueOf(a);
        String b1=String.valueOf(b);
        String c1=String.valueOf(c);
        String d1=String.valueOf(d);
        String e1=String.valueOf(e);
        String f1=String.valueOf(f);
        String code=a1+b1+c1+d1+e1+f1;
        EmailUtil emailUtil=new EmailUtil();
        String result=emailUtil.sendEmail(user.getEmail(),code,user.getName());
        System.out.println("resylt"+result);
        System.out.println("code"+code);
        return code;
    }

    //添加用户
    @RequestMapping(value = "/addUser" ,method = RequestMethod.POST)
    public Integer getCount(User user){
        System.out.println("user1111111111"+user.toString());
        String newPassword = new SimpleHash("md5", user.getPassword(),  ByteSource.Util.bytes(user.getPassword()), 2).toHex();
        user.setPassword(newPassword);
        System.out.println("user"+user.toString());
        Integer count=userService.addUser(user);
        return count;
    }
}
